<?php
declare (strict_types=1);

namespace app\api\model;

use app\common\model\User as UserModel;
use app\common\model\user\Grade as GradeModel;
use app\common\enum\user\grade\log\ChangeType as ChangeTypeEnum;
use think\facade\Request;
use think\facade\Db;

/**
 * 用户模型
 * Class User
 * @package app\api\model
 */
class User extends UserModel
{
    // 用于生成token的自定义盐
    const TOKEN_SALT = '4e81abe27cb4fb91';
    
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'create_time',
        'update_time'
    ];

    /**
     * 获取登录的信息
     * @return mixed
     */
    public static function getLoginInfo()
    {
        if (($token = self::getToken()) !== false) {
            $token = openssl_decrypt($token,'AES-128-CBC', md5(Request::domain()), 0, self::TOKEN_SALT);
            if($token == ''){
                return false;
            }
            $data = json_decode($token, true);
            if($data['timestamp']>0 && $data['timestamp']<time()){
                return false;
            }
            $user = UserModel::detail($data['user_id'])->toArray();
            $avatar = get_file_url($user['avatar']);
            if(count($avatar) > 0){
                $user['avatar'] = $avatar[0]['url'];
            }
            $user['currentOauth'] = Db::name('user_oauth')->where([
                ['user_id', '=', $data['user_id']],
                ['oauth_type', '=', $user['platform']]
            ])->find();
            return $user;
        }
        return false;
    }

    /**
     * 记录登录信息
     * @param array $userInfo
     * @return string
     */
    public static function login(int $userId): string
    {
        $data = [
            'user_id' => (int)$userId,
            'timestamp' => time()+86400*30
        ];
        return openssl_encrypt(json_encode($data),'AES-128-CBC', md5(Request::domain()), 0, self::TOKEN_SALT);
    }

    /**
     * 获取用户认证Token
     * @return bool|string
     */
    private static function getToken()
    {
        // 获取请求中的token
        $token = request()->header('Authorization');
        // 调试模式下可通过param
        if (empty($token) && is_debug()) {
            $token = request()->param('Authorization');
            // if (empty($token)) {
            //     $token = 'WIVuP8+GfKKBofOhq1gcw+g1HErkb38T+EklYQ/L3v5wSBpoLqiCgb7iD+8Z9zNe';
            // }
        }
        // 不存在token报错
        if (empty($token)) {
            return false;
        }
        return $token;
    }

    /**
     * 获取器：隐藏手机号中间四位
     * @param string $value
     * @return string
     */
    public function getMobileAttr(string $value): string
    {
        return strlen($value) === 11 ? hide_mobile($value) : $value;
    }

    public function edit($data): bool
    {
        if(isset($data['mobile'])){
            unset($data['mobile']);
        }
        return $this->save($data) !== false;
    }

}
